package com.rayboot.footpoint.view;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.rayboot.footpoint.R;
import com.rayboot.footpoint.model.Footprint;
import com.rayboot.footpoint.utils.StorageUtil;
import com.rayboot.footpoint.utils.Util;
import com.rayboot.footpoint.utils.voice.Recorder;

public class MediaControlPanelEditMode extends LinearLayout {
	private static final String TAG = "MediaControlPanelEditMode";

	OnClickListener deleteListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (mRecorder == null || mRecorder.sampleFile() == null) {
				Util.showToast(MediaControlPanelEditMode.this.getContext(),
						R.string.no_voice_data);
				return;
			}

			new AlertDialog.Builder(MediaControlPanelEditMode.this.getContext())
					.setTitle(R.string.text_delete_caption)
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setMessage(R.string.delete_voice)
					.setNegativeButton(R.string.text_cancel,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							})
					.setPositiveButton(R.string.button_ok,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
									mRecorder.delete();
									if (mFootprint != null) {
										mFootprint.mAudioFileName = null;
										mFootprint.mAudioPath = null;
										mProgress.setProgress(0);
										updateUI();
									}
								}
							}).show();
		}
	};

	public int mCurrentState;
	TextView mCurrentTime = null;
	ImageView mDeleteButton = null;
	Footprint mFootprint = null;
	final Handler mHandler = new Handler();
	SwitchButton mPlayButton = null;
	ProgressBar mProgress = null;
	SwitchButton mRecordButton = null;
	Recorder mRecorder = null;
	private long mRemainingTime = -1L;
	TextView mTotalTime = null;
	Runnable mUpdateTimer = new Runnable() {
		@Override
		public void run() {
			updateTimerView();
		}
	};

	Recorder.OnStateChangedListener mediaListener = new Recorder.OnStateChangedListener() {

		@Override
		public void onStateChanged(int state) {
			// TODO Auto-generated method stub
			mCurrentState = state;
			setScreenkeepOn(mCurrentState);
			updateUI();
		}

		@Override
		public void onError(int errorCode) {
			// TODO Auto-generated method stub
			int resId = 0;
			switch (errorCode) {
			case Recorder.SDCARD_ACCESS_ERROR:
				resId = R.string.error_sdcard_access;
				break;
			case Recorder.INTERNAL_ERROR:
				resId = R.string.error_app_internal;
				break;
			}
			if (resId == 0) {
				return;
			}

			new AlertDialog.Builder(MediaControlPanelEditMode.this.getContext())
					.setTitle(R.string.app_name)
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setMessage(resId)
					.setPositiveButton(R.string.button_ok, null)
					.setCancelable(false).show();
		}
	};

	SwitchButton.OnCheckedChangeListener playbackListener = new SwitchButton.OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(SwitchButton switchButton, boolean state) {
			// TODO Auto-generated method stub
			if (mRecorder == null || mRecorder.sampleFile() == null) {
				Util.showToast(MediaControlPanelEditMode.this.getContext(),
						R.string.no_voice_data);
				mPlayButton.setChecked(false);
				return;
			}

			if (state) {
				mRecorder.startPlayback();
			} else {
				mRecorder.stopPlayback();
			}
			updateUI();
		}
	};

	SwitchButton.OnCheckedChangeListener recordListener = new SwitchButton.OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(SwitchButton switchButton, boolean state) {
			// TODO Auto-generated method stub
			if (mRecorder == null) {
				mRecordButton.setChecked(false);
				return;
			}

			if (!StorageUtil.isExternalStorageEnough()
					|| !StorageUtil.isInternalStorageEnough()) {
				mRecordButton.setClickable(false);
				Util.showToast(MediaControlPanelEditMode.this.getContext(),
						R.string.text_not_enough_space);
				return;
			}

			if (state) {
				calRecordingTime();
				mTotalTime.setText(setupTimer(1000L * mRemainingTime));
				mRecorder.startRecording();
			} else {
				mRecorder.stopRecording();
			}

		}
	};

	public MediaControlPanelEditMode(Context context, AttributeSet attributeSet) {
		super(context, attributeSet);
		initView();
	}

	private void calRecordingTime() {
		long availableStorage = StorageUtil.availableStorage();
		long time;
		if (availableStorage > 0L) {
			time = availableStorage / 135L;
			mRemainingTime = time > 60L ? 60L : time;
		} else {
			mRemainingTime = -1L;
		}
	}

	private void setScreenkeepOn(int state) {
		switch (state) {
		case Recorder.IDLE_STATE:
			((Activity) getContext()).getWindow().addFlags(
					WindowManager.LayoutParams.ALPHA_CHANGED);
			break;
		case Recorder.RECORDING_STATE:
			((Activity) getContext()).getWindow().addFlags(
					WindowManager.LayoutParams.ALPHA_CHANGED);
			break;
		case Recorder.PLAYING_STATE:
			((Activity) getContext()).getWindow().addFlags(
					WindowManager.LayoutParams.ALPHA_CHANGED);
			break;
		case Recorder.PAUSE_STATE:
			((Activity) getContext()).getWindow().clearFlags(
					WindowManager.LayoutParams.ALPHA_CHANGED);
			break;

		default:
			break;
		}
	}

	private String setupTimer(long time) {
		if (time < 0L) {
			return "--:--";
		}
		return String.format("%02d:%02d", Long.valueOf(time / 1000L / 60L),
				Long.valueOf(time / 1000L % 60L));
	}

	private void updateButtonControl(int state) {
		switch (state) {
		case Recorder.IDLE_STATE:
			mRecordButton.setEnabled(true);
			mRecordButton.setChecked(false);
			mDeleteButton.setEnabled(true);
			mPlayButton.setEnabled(true);
			mPlayButton.setChecked(false);
			mProgress.setProgress(0);
			mCurrentTime.setText(setupTimer(0L));
			if (mRecorder == null) {
				return;
			}

			if (mRecorder.sampleFile() != null) {
				mTotalTime.setText(setupTimer(mRecorder.mSampleLength));
				mTotalTime.setVisibility(View.VISIBLE);
				mFootprint.mAudioPath = mRecorder.sampleFile()
						.getAbsolutePath();
				mFootprint.mAudioFileName = mRecorder.sampleFile().getName();
				invalidate();
			}
			mTotalTime.setText(setupTimer(-1L));
			mCurrentTime.setText(setupTimer(-1L));
			break;
		case Recorder.RECORDING_STATE:
			mRecordButton.setEnabled(true);
			mRecordButton.setChecked(false);
			mDeleteButton.setEnabled(true);
			mPlayButton.setEnabled(true);
			mPlayButton.setChecked(false);
			mProgress.setProgress(0);
			mCurrentTime.setText(setupTimer(0L));
			if (mRecorder == null) {
				return;
			}

			if (mRecorder.sampleFile() != null) {
				mTotalTime.setText(setupTimer(mRecorder.mSampleLength));
				mTotalTime.setVisibility(View.VISIBLE);
				mFootprint.mAudioPath = mRecorder.sampleFile()
						.getAbsolutePath();
				mFootprint.mAudioFileName = mRecorder.sampleFile().getName();
				invalidate();
			}
			mTotalTime.setText(setupTimer(-1L));
			mCurrentTime.setText(setupTimer(-1L));
			break;
		case Recorder.PLAYING_STATE:
			mRecordButton.setEnabled(false);
			mDeleteButton.setEnabled(false);
			mPlayButton.setEnabled(true);
			if (this.mRecorder == null) {
				return;
			}
			mCurrentTime.setText(setupTimer(mRecorder.progress()));
			mTotalTime.setText(setupTimer(mRecorder.mSampleLength));
			mTotalTime.setVisibility(View.VISIBLE);
			break;
		case Recorder.PAUSE_STATE:
			mRecordButton.setEnabled(false);
			mDeleteButton.setEnabled(false);
			mPlayButton.setEnabled(true);
			if (this.mRecorder == null) {
				return;
			}
			mCurrentTime.setText(setupTimer(mRecorder.progress()));
			mTotalTime.setText(setupTimer(mRecorder.mSampleLength));
			mTotalTime.setVisibility(View.VISIBLE);
			break;
		default:
			mRecordButton.setEnabled(true);
			mDeleteButton.setEnabled(false);
			mPlayButton.setEnabled(false);
			if (mRecorder == null) {
				return;
			}
			mCurrentTime.setText(setupTimer(mRecorder.progress()));
			mTotalTime.setVisibility(View.VISIBLE);

			mCurrentTime.setText(setupTimer(mRecorder.progress()));
			mTotalTime.setText(setupTimer(mRecorder.mSampleLength));
			break;
		}
	}

	private void updateTimerView() {
		if (mCurrentState == Recorder.RECORDING_STATE && mRecorder != null) {
			mCurrentTime.setText(setupTimer(mRecorder.progress()));
			mProgress.setProgress((int) (mProgress.getMax()
					* mRecorder.progress() / mRemainingTime / 1000L));
			if (mRecorder.progress() > 1000L * mRemainingTime) {
				mRecordButton.setChecked(false);
			}
		} else if (mCurrentState == Recorder.PLAYING_STATE) {
			mCurrentTime.setVisibility(View.VISIBLE);
			if (mRecorder != null) {
				long progressPos = mRecorder.progress();
				mCurrentTime.setText(setupTimer(progressPos));
				if (mRecorder.mSampleLength > 0) {
					mTotalTime
							.setText(setupTimer(this.mRecorder.mSampleLength));
					mProgress
							.setProgress((int) (1000L * progressPos / this.mRecorder.mSampleLength));
				}
			}
		} else if (mCurrentState == Recorder.PAUSE_STATE) {
			// int j = this.mCurrentTime.getVisibility();
			// localTextView = this.mCurrentTime;
			// if (j != 4)
			// break label298;
		}

		mHandler.postDelayed(mUpdateTimer, 500L);
	}

	private void updateUI() {
		updateButtonControl(mCurrentState);
		updateTimerView();
	}

	void initView() {
		addView(((LayoutInflater) getContext().getSystemService(
				Context.LAYOUT_INFLATER_SERVICE)).inflate(
				R.layout.media_panel_edit_mode, null));
		mDeleteButton = ((ImageView) findViewById(R.id.ivDelVoice));
		mDeleteButton.setOnClickListener(deleteListener);
		mRecordButton = ((SwitchButton) findViewById(R.id.sbRecordVoice));
		mRecordButton.setOnCheckedChangeListener(recordListener);
		mPlayButton = ((SwitchButton) findViewById(R.id.sbPlayVoice));
		mPlayButton.setOnCheckedChangeListener(playbackListener);
		mPlayButton.setOnClickListener(null);
		mCurrentTime = ((TextView) findViewById(R.id.tvCurTime));
		mCurrentTime.setText(setupTimer(-1L));
		mTotalTime = ((TextView) findViewById(R.id.tvTotalTime));
		mTotalTime.setText(setupTimer(-1L));
		mProgress = ((ProgressBar) findViewById(R.id.pbStateProgressBar));
	}

	public void resetState() {
	}

	public void setFootprintData(Footprint footprint) {
		if (footprint == null)
			return;
		this.mFootprint = footprint;

		if (mFootprint.mAudioPath == null) {
			mRecorder = new Recorder();
		} else {
			mRecorder = new Recorder(mFootprint.mAudioPath);
			mRecorder.setOnStateChangedListener(mediaListener);
			updateUI();
		}
	}

	public void stopMediaControlPanel() {
		updateButtonControl(Recorder.IDLE_STATE);
		if (mRecorder == null) {
			return;
		}

		mRecorder.stop();
		if (mFootprint != null && mRecorder.sampleFile() != null) {
			mFootprint.mAudioFileName = mRecorder.sampleFile().getName();
			mFootprint.mAudioPath = mRecorder.sampleFile().getAbsolutePath();
		}
	}
}
